package top.gradual.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;


/**
 * @Description: IP过滤器 Pre
 * @Author: gradual
 * @Date: 2019-06-27 23:29
 */
@Slf4j
public class IpFilter extends ZuulFilter {

    public IpFilter() {
        super();
    }


    /**
     * @description: 配置过滤器类型 (pre|route|post|error)
     * @author: gradual
     * @date: 2019-06-27 23:31
     * @param: []
     * @return: java.lang.String
     */
    @Override
    public String filterType() {
        return "pre";
    }


    /**
     * @description: 过滤器执行顺序，越小优先级越高
     * @author: gradual
     * @date: 2019-06-27 23:31
     * @param: []
     * @return: int
     */
    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * @description: 是否执行该过滤器
     * @author: gradual
     * @date: 2019-06-27 23:32
     * @param: []
     * @return: boolean
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * @description: 执行自己的业务逻辑
     * @date: 2019/6/28 11:02
     * @author: gradual
     * @return: java.lang.Object
     */
    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        log.info("filter");
        String requestURI = requestContext.getRequest().getRequestURI();
        log.info("uri:" + requestURI);
        if (requestURI.endsWith("error")) {
            System.out.println(2/0);
        }
        //告诉Zuul不需要将当前请求转发到后端的服务
        if (requestURI.endsWith("0")) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseBody("gg");
            requestContext.getResponse().setContentType("application/json; charset=utf-8");
            return null;
        }
        return null;
    }
}
